<?php
class User_Plugin_Auth_Acl extends Zend_Acl
{
    public function __construct()
    {
        self::roleResource();
    }

    private function initRoles()
    {
       $obj_role = new User_Model_DbTable_Role();  
       $roles = $obj_role->fetchAll($obj_role->select()->order('id DESC'))->toArray();
        foreach ($roles as $r) {
           $this->addRole(new Zend_Acl_Role($r['role_name']));
        }
        
    }

    private function initResources()
    {
     
        self::initRoles();

        $obj_resource = new User_Model_DbTable_AclResource();
        $resources = $obj_resource->fetchAll($obj_resource->select())->toArray();

        $module = '';
      
        foreach ($resources as $key=>$value)
		{
           
            if ($value['resource'])
			{
                $arr_resource = explode("_",$value['resource']);
            
                if(!$module)
                {
                    $this->add(new Zend_Acl_Resource($arr_resource[0]));
                    $module = $arr_resource[0];
                }

                $this->add(new Zend_Acl_Resource($value['resource'],$arr_resource[0]));
            }
           
        }
    }

    private function roleResource()
    {
        
        self::initResources();
		$obj_role = new User_Model_DbTable_Role();
		$obj_resource = new User_Model_DbTable_AclResource();
		$obj_permission = new User_Model_DbTable_Aclpermission();
        $db  =  Zend_Db_Table::getDefaultAdapter();
        $acl = $db->fetchAll(
               $db->select()
                    ->from($obj_role->_name. ' as r')
                    ->from($obj_resource->_name. ' as res')
                    ->from($obj_permission->_name. ' as p')
                    ->where('r.id = p.role_id and p.resource_id = res.id'));
        
        foreach ($acl as $key=>$value) {
            $this->allow($value['role_name'], $value['resource'],$value['permission']);
        }
    }
}